﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sinacor.Infra.Tools.ServiceRegistration.Business
{
    public class Service
    {
        #region Attributes

        private Data.Service _resourceAccess;
        private Data.EndPoint _resourceAccessEndPoint; 
        private object locker = new object();

        #endregion

        #region Constructor

        public Service()
        {
            this._resourceAccess = new Data.Service();
            this._resourceAccessEndPoint = new Data.EndPoint();
        }

        #endregion

        #region Methods

        public List<Entity.Service> SelectService(Entity.Service entity)
        {
            return _resourceAccess.SelectService(entity, true);
        }

        public Entity.Service PersistService(Entity.Service entity)
        {
            Entity.Service service = new Entity.Service() { ServiceName = entity.ServiceName, SubModule = entity.SubModule };
            List<Entity.Service> services = null;

            services = _resourceAccess.SelectService(service, false);

            if (services.Count == 0)
            {
                service = InsertService(entity);
            }
            else
            {
                service = services[0];

                if (service.StatusApproval == Entity.StatusApproval.AguardandoAprovacao && !string.IsNullOrEmpty(entity.Description))
                    service.Description = entity.Description;

                service.DateChange = entity.DateChange;
                service.DataOrigin = entity.DataOrigin;
                UpdateService(service);
            }

            return service;
        }

        public Entity.Service InsertService(Entity.Service entity)
        {
            entity.ServiceId = this.GetNextServiceId();
            return _resourceAccess.InsertService(entity);
        }

        public void UpdateService(Entity.Service entity)
        {
            _resourceAccess.UpdateService(entity);

            _resourceAccessEndPoint.DeleteEndPointByServiceId(new Entity.EndPoint() { Service = (new Entity.Service() { ServiceId = entity.ServiceId }) });
            foreach (Entity.EndPoint endPointItem in entity.EndPoints)
            {
                endPointItem.EndPointId = _resourceAccessEndPoint.GetNextEndPointId();
                endPointItem.ContractName = "I" + entity.ServiceName; 
                _resourceAccessEndPoint.InsertEndPoint(endPointItem);
            }
        }

        public void DeleteService(Entity.Service entity)
        {
            _resourceAccess.DeleteService(entity);
        }

        public int GetNextServiceId()
        {
            int nextId = 0;

            lock (locker)
            {
                nextId = _resourceAccess.GetNextServiceId();
            }

            return nextId;
        }

        #endregion
    }
}
